package cn.micro.system.manage.controller;
import cn.micro.system.manage.common.enums.BusinessTypeEnum;
import cn.micro.system.manage.common.log.annotation.Log;
import cn.micro.system.manage.common.log.enums.BusinessType;
import cn.micro.system.manage.common.result.Result;
import cn.micro.system.manage.common.security.utils.SecurityUtil;
import cn.micro.system.manage.entity.AssetOdsFileRecordUseRelation;
import cn.micro.system.manage.entity.SysDimUser;
import cn.micro.system.manage.entity.SysDimUserRole;
import cn.micro.system.manage.entity.dto.UpdatePasswordDTO;
import cn.micro.system.manage.service.AssetOdsFileRecordUseRelationService;
import cn.micro.system.manage.service.OssService;
import cn.micro.system.manage.service.SysDimUserRoleService;
import cn.micro.system.manage.service.SysDimUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/manage/userCenter")
@RequiredArgsConstructor
public class UserCenterController {

    private final SysDimUserService sysDimUserService;

    private final SysDimUserRoleService sysDimUserRoleService;

    private final OssService ossService;

    private final AssetOdsFileRecordUseRelationService useRelationService;

    @GetMapping("info")
    public Object info(){
        SysDimUser sysDimUser = sysDimUserService.getById(SecurityUtil.getUserId());
        sysDimUser.setPassword(null);
        return Result.success(sysDimUser);
    }

    @PutMapping("edit")
    @Log(title = "个人中心管理--修改个人信息",businessType = BusinessType.UPDATE)
    public Object edit(@RequestBody SysDimUser sysDimUser){
        sysDimUser.setId(String.valueOf(SecurityUtil.getUserId()));
        if (!sysDimUserService.updateById(sysDimUser)){
            return Result.fail();
        }
        return Result.success();
    }

    @PutMapping("updatePassword")
    @Log(title = "个人中心管理--修改登录密码",businessType = BusinessType.UPDATE,isSaveRequestData = false)
    public Object updatePassword(@RequestBody UpdatePasswordDTO dto){
        SysDimUser sysDimUser = sysDimUserService.getById(SecurityUtil.getUserId());
        if (!SecurityUtil.matchesPassword(dto.getOldPassword(), sysDimUser.getPassword())){
            return Result.fail("旧密码错误");
        }
        sysDimUser.setPassword(SecurityUtil.encryptPassword(dto.getNewPassword()));
        if (!sysDimUserService.updateById(sysDimUser)){
            return Result.fail();
        }
        return Result.success();
    }

    @DeleteMapping("delete")
    @Log(title = "个人中心管理--注销个人信息",businessType = BusinessType.DELETE)
    public Object delete(){
        sysDimUserRoleService.remove(new LambdaQueryWrapper<SysDimUserRole>().eq(SysDimUserRole::getUserId, SecurityUtil.getUserId()));
        if (!sysDimUserService.removeById(SecurityUtil.getUserId())){
            return Result.fail();
        }
        return Result.success();
    }

    @GetMapping("validateUsername/{username}")
    public Object validateUsername(@PathVariable String username){
        SysDimUser sysDimUser = sysDimUserService.getOne(new LambdaQueryWrapper<SysDimUser>().eq(SysDimUser::getUsername, username).ne(SysDimUser::getId, SecurityUtil.getUserId()));
        return Result.success(sysDimUser == null);
    }

    /**
     * 上传头像功能
     * @param file
     * @return
     */
    @PostMapping("uploadAvatar")
    @Log(title = "个人中心管理--上传头像",businessType = BusinessType.UPDATE)
    @Transactional
    public Object uploadAvatar(MultipartFile file){
        MultipartFile[] files = new MultipartFile[1];
        files[0] = file;
        List<String> upload = ossService.upload(files, "/user/avatar");
        if (upload.size() > 0){
            //查询是否已存在该头像信息--如已存在--则更新
            LambdaQueryWrapper<AssetOdsFileRecordUseRelation> wrapper = new LambdaQueryWrapper<AssetOdsFileRecordUseRelation>().eq(AssetOdsFileRecordUseRelation::getUseId, SecurityUtil.getUserId()).eq(AssetOdsFileRecordUseRelation::getBusinessType, BusinessTypeEnum.USER_AVATAR_BUSINESS.getValue());
            AssetOdsFileRecordUseRelation useRelation = useRelationService.getOne(wrapper);
            if (useRelation != null){
                useRelation.setFileId(Long.parseLong(upload.get(0)));
                useRelation.setCreateTime(LocalDateTime.now());
                if (useRelationService.updateById(useRelation)){
                    return Result.success();
                }
            }else {
                useRelation = new AssetOdsFileRecordUseRelation();
                useRelation.setUseId(SecurityUtil.getUserId().toString());
                useRelation.setFileId(Long.parseLong(upload.get(0)));
                useRelation.setBusinessType(BusinessTypeEnum.USER_AVATAR_BUSINESS.getValue());
                if (useRelationService.save(useRelation)){
                    return Result.success();
                }
            }
        }
        return Result.fail();
    }



}
